package com.pzhu.servlet;

import com.pzhu.controller.BookController;
import com.pzhu.controller.impl.BookControllerImpl;
import com.pzhu.pojo.Book;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class AddBookServlet extends HttpServlet {
    private BookController bookController = new BookControllerImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session =req.getSession();
        if (session.getAttribute("login") == null) {
            req.getRequestDispatcher("/main").forward(req, resp);
            return;
        }
        Book book = new Book();
        book.setId(Long.parseLong((req.getParameter("id"))));
        book.setName(req.getParameter("name"));
        book.setAuthor(req.getParameter("author"));
        book.setLanguage((req.getParameter("language")));
        book.setClassId((req.getParameter("classId")));
        book.setPublish(req.getParameter("publish"));
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        try {
            book.setPubDate((ft.parse(req.getParameter("publishDate"))));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        book.setPrice(Double.parseDouble(req.getParameter("price")));
        book.setNumber(Integer.parseInt(req.getParameter("number")));
        book.setISBN(Long.valueOf(req.getParameter("isbn")));
        book.setIntroduction(req.getParameter("introduction"));
        book.setUpdateUser(Long.parseLong(req.getParameter("update")));
        bookController.addBook(book);
        req.setAttribute("bookList", bookController.selectAllBook());
        req.getRequestDispatcher("/view/jsp/book/showAllBooks.jsp").forward(req, resp);
    }
}
